package com.vf.cloud.paas.app.agent.common.server.signalling.channel;

import java.util.concurrent.TimeUnit;

import com.vf.cloud.paas.app.agent.common.server.signalling.handler.StreamerChannelInboundHandlerHandler;
import com.vf.cloud.paas.common.service.IRedis;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

public class StreamerChannelInitializer extends ChannelInitializer<SocketChannel> {

	private String awsIp;
	private boolean enabled;
	private int streamerPort;
	private int stunPort;
	private int tunPort;
	private String username;
	private String password;
	private String localIp;
	private int idleTimeout;
	private IRedis redisImpl;

	public StreamerChannelInitializer(IRedis redisImpl,int streamerPort,String awsIp,boolean enabled, int stunPort, int tunPort, String username, String password,
			String localIp,int idleTimeout) {
		super();
		this.awsIp=awsIp;
		this.enabled = enabled;
		this.stunPort = stunPort;
		this.tunPort = tunPort;
		this.username = username;
		this.password = password;
		this.localIp = localIp;
		this.idleTimeout=idleTimeout;
		this.redisImpl=redisImpl;
		this.streamerPort=streamerPort;
	}

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ch.pipeline()
				// 设置30秒没有读到数据，则触发一个READER_IDLE事件。
				.addLast(new IdleStateHandler(0, 30, 0, TimeUnit.SECONDS))
				// HttpServerCodec：将请求和应答消息解码为HTTP消息
				.addLast(new HttpServerCodec()).addLast(new StringEncoder())// 添加字符串编码器
				// HttpObjectAggregator：将HTTP消息的多个部分合成一条完整的HTTP消息
				.addLast(new HttpObjectAggregator(65536))
				// ChunkedWriteHandler：向客户端发送HTML5文件
				.addLast(new ChunkedWriteHandler())
				// .addLast(new WebSocketServerProtocolHandler("/", "ws", true, 65536 * 10))
				.addLast(new StreamerChannelInboundHandlerHandler(redisImpl,streamerPort,awsIp,enabled, stunPort, tunPort, username, password,
						localIp,idleTimeout));
	}

}
